//#define _CRTDBG_MAP_ALLOC
#include "StdAfx.h"
#include "DBConnect.h"
#include "Frame.h"
//#define _CRTDBG_MAP_ALLOC

//#include <sql.h>
//#include <sqlext.h>
//#include <mysql++.h>




DBConnect::DBConnect(char* server, char* dbName, char* userName, char* password)
{
	this->server = server;
	this->dbName = dbName;
	this->username = userName;
	this->password = password; 
	if(connect()){
		printf("connected\n");
	} else {
		printf("not connected\n");
		//printf(this->conn->);
	}
}

DBConnect::~DBConnect(void)
{
mysql_close(conn);


/*delete this->dbName;
delete this->username;
delete this->password;*/

	/*conn->disconnect();
	conn->~Connection();*/
	//delete conn;
	/*delete this->conn;
	delete this->server;
	delete this->dbName;
	delete this->username;
	delete this->password;*/
}


bool DBConnect::connect(){

//try {

   conn = mysql_init(NULL);
   // printf("MySQL client version: %s\n", mysql_get_client_info());
   
    if (mysql_real_connect(conn, this->server, this->username, this->password, this->dbName, 0, NULL, 0) == NULL) {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
    }


   /*driver = get_driver_instance();

   conn = driver->connect(this->server,this->username, this->password);
   conn->setSchema(this->dbName);
   */
  // conn -> setAutoCommit(0);

   
     /*stmt = conn->createStatement();
    res = stmt->executeQuery("SELECT siftfeatures from image where id=4");
    
    while (res->next()) {
        cout << res->getst << endl;

    
    }*/


/*} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
  return false;
}*/
return true;
	//conn = new mysqlpp::Connection(false);
	//return (conn->connect(this->dbName, this->server, this->username, this->password));
	//return true;
}

void DBConnect::disconnect(){
	//conn->disconnect();
	//delete conn;
}

MYSQL* DBConnect::getConnection(){
	/*if(!this->conn->connected()){
		this->conn->disconnect();
		this->conn->connect();
		if(this->conn->ping())
			printf("responding");
	} */
	return this->conn;
}

void DBConnect::storeMovingImage(char* address,IplImage* image,time_t* time)
{
  //int imageChunkSize = 2*strlen(image->imageData)+1;
  int imageChunkSize = 3*image->widthStep*image->height;
  char* chunkMovingImage=(char*)malloc(sizeof(char)*imageChunkSize);    
 //   IplImage* image=snapshot ;
   // MYSQL *conn = dbConnect->getConnection();
  // printf("Image Data Size: %d, Image Size: %d\n",strlen(image->imageData),image->width*image->height);
  mysql_escape_string(chunkMovingImage,image->imageData,imageChunkSize/3);     // image->imageData /2   conn,
  
  //char* stat = "INSERT INTO image (camaraIp,movingSegment,movingSegmentWidth,movingSegmentHeight,secfrom70) values('%s','%s',%d,%d,%d)";
  char* stat = "INSERT INTO image (camaraIp,movingSegment,movingSegmentWidth,movingSegmentHeight,secfrom70) values('%s','%s',%d,%d,%ld)";
  char* query=(char*)malloc(sizeof(char)*(strlen(stat)+imageChunkSize));
  int len = sprintf(query,stat,address,chunkMovingImage,image->width,image->height,*time);
  
 //  printf("Image Data Size: %d Diff:%d\n",strlen(image->imageData),(len-imageChunkSize/3));
   
 // cout<<"Time 03 :"<<*time<<endl; 
 // cout<<"Querry :"<<query<<endl;
   mysql_real_query(conn, query, len);
   
       free(query);
    free(chunkMovingImage);  

}
vector<IplImage*> DBConnect::loadByCameraDate(char* ipAddrss,time_t* dateTime)
{
   // IplImage** returnImageCollection=0;
    
    vector<IplImage*> returnVector;
   // vector<IplImage*>::iterator it;
      
    //IplImage* image=0;
     unsigned long *lengths;
     char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,id FROM image WHERE camaraIp='%s' and secfrom70>%ld";
     
     char* ipAddrssWithEscape = (char*)malloc(sizeof(char)*strlen(ipAddrss)*2);  
     mysql_escape_string(ipAddrssWithEscape, ipAddrss, strlen(ipAddrss));    //conn mysql_real_escape_string
     
    
     
   // cout<<strlen(sql)<<" "<<strlen(ipAddrssWithEscape)<<strlen(ipAddrss)<<" "<<sizeof(long int)<<endl;
        
     char* query=(char*)malloc(sizeof(char)*(strlen(sql)+strlen(ipAddrssWithEscape)+sizeof(dateTime)*8));
     
     int len = sprintf(query,sql, ipAddrssWithEscape,*dateTime); 
      // free(query);
     
// MYSQL *conn = dbConnect->getConnection();
     mysql_query(conn, query);
     MYSQL_RES *result = mysql_store_result(conn);
     //MYSQL_ROW  row = mysql_fetch_row(result);
      MYSQL_ROW  row;
     //lengths = mysql_fetch_lengths(result);
    int numFields = mysql_num_fields(result);
    int numRows = mysql_num_rows(result);
    
   /* if (returnImageCollection==0)
   {
        returnImageCollection = new IplImage*[numRows];
        for (int j=0;j<numRows;j++)
        {
            returnImageCollection[j]=0;
        }
    }*/
   //  it = returnVector.begin();
     
     int j=0;   
     while ((row = mysql_fetch_row(result)))
     {
       // lengths = mysql_fetch_lengths(row);
        
        int width=0;
        if(row[1]!=NULL)
        {
            width = atoi(row[1]);
           /* char* rowFromDB = (char*)malloc(sizeof(char)*lengths[0]);
            memcpy(rowFromDB,row[0],(sizeof(char)*lengths[0]));*/
        }
        int height=0;
        if(row[2]!=NULL)
        {
            height = atoi(row[2]);
        }
        int id=0;
        if(row[3]!=NULL)
        {
                id =  atoi(row[3]);
                cout<<j<<". Id from DB: "<<id<<endl;
        
        }
       if(row[0]!=NULL)
        {
            IplImage* image = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
            image->imageData= (char*)malloc(sizeof(char)*width*height);
            
           // char* rowFromDB = (char*)malloc(sizeof(char)*width*height);
            memcpy(image->imageData,row[0],(sizeof(char)*width*height));
            
            
        
            

           // image->imageData = rowFromDB;
            
           // returnImageCollection[j] = image;
            j++;
            
            /*cvShowImage("FromDB1",image);
            
             if( cvWaitKey(10) >= 0 )                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                           break;*/
           // this->cameraIp=rowFromDB;
     
           // free(rowFromDB);
            
             //it =returnVector.insert(it,image);
             returnVector.push_back(image);
             //for(std::vector<IplImage*>::iterator it = returnVector.begin(); it != returnVector.end(); ++it)
             //{
             //  // IplImage* imageVectorItem= (IplImage*)*it;
             //   IplImage* imageVectorItem= (IplImage*)returnVector.end();
             //    cvWaitKey(0);
             // }
        //    free(query);
        }
     
     
     }
     free(query);
     free(ipAddrssWithEscape);
     
    //delete   query;
    /*for (int i=0; i<numRows; i++)
    {
         cvShowImage("FromDB",returnImageCollection[i]);
         cvWaitKey(0);
    }*/
    /* for (int i=0; i<returnVector.size(); i++)
     {
          IplImage* imageVectorItem= returnVector[i];
          cvShowImage("From Vector",imageVectorItem);
         cvWaitKey(0);
     } */
     /*for(std::vector<IplImage*>::iterator it = returnVector.begin(); it != returnVector.end(); ++it)
     {
        IplImage* imageVectorItem= (IplImage*)*it;
         cvShowImage("From DB",imageVectorItem);
         cvWaitKey(0);
      }*/
    
      return returnVector;
       //return 0;
      //return returnImageCollection;

}
  vector<int> DBConnect::loadImageIDByDate(time_t* dateTime)
//vector<IplImage*> DBConnect::loadByDate(time_t* dateTime)
{
    vector<int> returnVector;
   // vector<IplImage*>::iterator it;
      
    //IplImage* image=0;
     unsigned long *lengths;
     //char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,id,timestamp FROM image WHERE secfrom70>%ld";
     char* sql = "SELECT id FROM image WHERE secfrom70>%ld";
         
     char* query=(char*)malloc(sizeof(char)*(strlen(sql)+sizeof(dateTime)*8));
     
     int len = sprintf(query,sql,*dateTime); 
      // free(query);
     
// MYSQL *conn = dbConnect->getConnection();
     mysql_query(conn, query);
     MYSQL_RES *result = mysql_store_result(conn);
     //MYSQL_ROW  row = mysql_fetch_row(result);
      MYSQL_ROW  row;
     //lengths = mysql_fetch_lengths(result);
    int numFields = mysql_num_fields(result);
    int numRows = mysql_num_rows(result);
    
   
    
    

     
     int j=0;   
     while ((row = mysql_fetch_row(result)))
     {
          lengths = mysql_fetch_lengths(result);
        
        int width=0;
       /* if(row[1]!=NULL)
        {
            width = atoi(row[1]);

        }
        int height=0;
        if(row[2]!=NULL)
        {
            height = atoi(row[2]);
        }
        int id=0;
        if(row[3]!=NULL)
        {
                id =  atoi(row[3]);
                cout<<j<<". Id from DB: "<<id<<endl;
        
        }
        time_t time;
        if(row[4]!=NULL)
        {
            row[4];
               // id =  atoi(row[3]);
               // cout<<j<<". Id from DB: "<<id<<endl;
        
        }  */
        int id=0;
       if(row[0]!=NULL)
        {

           
            //image->imageData= (char*)malloc(sizeof(char)*width*height);
           // image->imageData= (char*)malloc(sizeof(char)*lengths[0]);
            
            // printf("Size of the image from DB :%d , Original Size :%d\n",sizeof(char)*lengths[0],width*height);
            
           // image->ID =id; 
            
           // image->widthStep = 920;
          
           /* if(j==17)
            {
                 cvShowImage("From DB",image);
                cvWaitKey(5);
                printf("ID :%d\n",id);
            }*/
             
             // image->imageDataOrigin=  (char*) row[0];
           // memcpy(image->imageData,row[0],sizeof(char)*lengths[0]);              //(sizeof(char)*width*height)
                  
            /*char jString[50];
             sprintf(jString,"DB%d.jpg",j);          
                                    
           cvSaveImage(jString,image);
          cvShowImage("From DB",image);
            cvWaitKey(0); */
           //  Frame* frame = new Frame();
           //   frame->setFrame(image);
            //  frame->setTime(  
            
                      
            /* IplImage* image = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
              image->imageData= (char*) row[0];
            j++;
            

             returnVector.push_back(image);*/
              id =  atoi(row[0]);
              returnVector.push_back(id);
              
 
        }
     
     
     }
     mysql_free_result(result);
     free(query);


   
    
      return returnVector;
      

}

 vector<int> DBConnect::loadImageIDByCameraDate(char* ipAddrss,time_t* dateTime)
 {
        vector<int> returnVector;

       unsigned long *lengths;
       //char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,id,timestamp FROM image WHERE secfrom70>%ld";
       char* sql = "SELECT id FROM image WHERE camaraIp='%s' and secfrom70>%ld";
         
      char* query=(char*)malloc(sizeof(char)*(strlen(sql)+strlen(ipAddrss)+sizeof(dateTime)*8));
     
      int len = sprintf(query,sql,ipAddrss,*dateTime); 
  
      mysql_query(conn, query);
      MYSQL_RES *result = mysql_store_result(conn);
      //MYSQL_ROW  row = mysql_fetch_row(result);
      MYSQL_ROW  row;
      //lengths = mysql_fetch_lengths(result);
      int numFields = mysql_num_fields(result);
      int numRows = mysql_num_rows(result);
      
      int j=0;   
      while ((row = mysql_fetch_row(result)))
      {
          lengths = mysql_fetch_lengths(result);
        
          int width=0;
          
          int id=0;
          if(row[0]!=NULL)
          {
               id =  atoi(row[0]);
               returnVector.push_back(id);
          
          }
        
        
      }
      mysql_free_result(result);
      free(query);
      
      return returnVector;
 }
 
  vector<int> DBConnect::loadImageIDByCameraDuration(char* ipAddrss,int dateTimeFromSecFrom70,int dateTimeToSecFrom70)
 {
        vector<int> returnVector;

       unsigned long *lengths;
       //char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,id,timestamp FROM image WHERE secfrom70>%ld";
       char* sql = "SELECT id FROM image WHERE camaraIp='%s' and secfrom70>%d and secfrom70<%d";
         
      char* query=(char*)malloc(sizeof(char)*(strlen(sql)+strlen(ipAddrss)+sizeof(dateTimeFromSecFrom70)*16+sizeof(dateTimeToSecFrom70)*16));
     
      //int len = sprintf(query,sql,ipAddrss,*dateTimeFrom,*dateTimeTo); 
      int len = sprintf(query,sql,ipAddrss,dateTimeFromSecFrom70,dateTimeToSecFrom70); 
  
      mysql_query(conn, query);
      MYSQL_RES *result = mysql_store_result(conn);
      //MYSQL_ROW  row = mysql_fetch_row(result);
      MYSQL_ROW  row;
      //lengths = mysql_fetch_lengths(result);
      int numFields = mysql_num_fields(result);
      int numRows = mysql_num_rows(result);
      
      int j=0;   
      while ((row = mysql_fetch_row(result)))
      {
          lengths = mysql_fetch_lengths(result);
        
          int width=0;
          
          int id=0;
          if(row[0]!=NULL)
          {
               id =  atoi(row[0]);
               returnVector.push_back(id);
          
          }
        
        
      }
      mysql_free_result(result);
      free(query);
      
      return returnVector;
 }
 
 vector<int> DBConnect::loadImageIDWithMatchIdZero()
 {
      vector<int> returnVector;

       unsigned long *lengths;
       //char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,id,timestamp FROM image WHERE secfrom70>%ld";
      // char* sql = "SELECT id FROM image WHERE matchId=0";
         
      //char* query=(char*)malloc(sizeof(char)*(strlen(sql)));
     
    //  int len = sprintf(query,sql,ipAddrss,*dateTime); 
  
      mysql_query(conn, "SELECT id FROM image WHERE matchId=0 order by secfrom70");
      MYSQL_RES *result = mysql_store_result(conn);
      //MYSQL_ROW  row = mysql_fetch_row(result);
      MYSQL_ROW  row;
      //lengths = mysql_fetch_lengths(result);
      int numFields = mysql_num_fields(result);
      int numRows = mysql_num_rows(result);
      int j=0;   
      while ((row = mysql_fetch_row(result)))
      {
          lengths = mysql_fetch_lengths(result);
        
          int width=0;
          
          int id=0;
          if(row[0]!=NULL)
          {
               id =  atoi(row[0]);
               returnVector.push_back(id);
          
          }
        
        
      }
      mysql_free_result(result);
     // free(query);
     
      
      return returnVector;
 }
 

IplImage* DBConnect::loadImageCameraIPById(char* cameraIp,int* secFrom70, int id)
{
    IplImage* returnImage=0;
     unsigned long *lengths;
    
     char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight,camaraIp,secfrom70 FROM image WHERE id='%d'";
         
     char* query=(char*)malloc(sizeof(char)*(strlen(sql)+sizeof(id)*8));
     
     int len = sprintf(query,sql,id); 
     
     mysql_query(conn, query);
     MYSQL_RES *result = mysql_store_result(conn);
     MYSQL_ROW  row;
    int numFields = mysql_num_fields(result);
    int numRows = mysql_num_rows(result);
    
    while ((row = mysql_fetch_row(result)))
     {
          lengths = mysql_fetch_lengths(result);
        
        int width=0;
        if(row[1]!=NULL)
        {
            width = atoi(row[1]);

        }
        int height=0;
        if(row[2]!=NULL)
        {
            height = atoi(row[2]);
        }
       /*char* cameraIp;  */
        if(row[3]!=NULL)
        {
                //cameraIp = (char*) row[3];
                //  cameraIp = (char*)malloc(sizeof(char)*lengths[3]);
                strcpy(cameraIp, row[3]);
                
                 //memcpy(cameraIp,row[3],sizeof(char)*lengths[3]);          
        }
        
      //  time_t time;
        if(row[4]!=NULL)
        {
            
           // secFrom70 = new time_t(atoi(row[4]));
           *secFrom70 = atoi(row[4]);
          //  memcpy(secFrom70,(void*)atoi(row[4]),sizeof(int));
        //    row[4];
        //       // id =  atoi(row[3]);
        //       // cout<<j<<". Id from DB: "<<id<<endl;
        //
        }  
       if(row[0]!=NULL)
        {

           
            //image->imageData= (char*)malloc(sizeof(char)*width*height);
           // image->imageData= (char*)malloc(sizeof(char)*lengths[0]);
            
            // printf("Size of the image from DB :%d , Original Size :%d\n",sizeof(char)*lengths[0],width*height);
            
           // image->ID =id; 
            
           // image->widthStep = 920;
          
           /* if(j==17)
            {
                 cvShowImage("From DB",image);
                cvWaitKey(5);
                printf("ID :%d\n",id);
            }*/
             
             // image->imageDataOrigin=  (char*) row[0];
           // memcpy(image->imageData,row[0],sizeof(char)*lengths[0]);              //(sizeof(char)*width*height)
                  
            /*char jString[50];
             sprintf(jString,"DB%d.jpg",j);          
                                    
           cvSaveImage(jString,image);
          cvShowImage("From DB",image);
            cvWaitKey(0); */
           //  Frame* frame = new Frame();
           //   frame->setFrame(image);
            //  frame->setTime(  
            
                      
             IplImage* image = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
             memcpy(image->imageData,row[0],sizeof(char)*lengths[0]);
             // image->imageData= (char*) row[0];
            //j++;
              image->ID =id;
              
              returnImage = image;
            // returnVector.push_back(image);
            }
             
              
 
     }
     mysql_free_result(result);
      free(query);
     // free(sql);
     return returnImage;
}

IplImage* DBConnect::loadImageById(int id)
{
    IplImage* returnImage=0;
     unsigned long *lengths;
    
     char* sql = "SELECT movingSegment,movingSegmentWidth,movingSegmentHeight FROM image WHERE id='%d'";
         
     char* query=(char*)malloc(sizeof(char)*(strlen(sql)+sizeof(id)*8));
     
     int len = sprintf(query,sql,id); 
     
     mysql_query(conn, query);
     MYSQL_RES *result = mysql_store_result(conn);
     MYSQL_ROW  row;
    int numFields = mysql_num_fields(result);
    int numRows = mysql_num_rows(result);
    
    while ((row = mysql_fetch_row(result)))
    {
        lengths = mysql_fetch_lengths(result);
        
        int width=0;
        if(row[1]!=NULL)
        {
            width = atoi(row[1]);

        }
        int height=0;
        if(row[2]!=NULL)
        {
            height = atoi(row[2]);
        }

       if(row[0]!=NULL)
       {                    
                      
             IplImage* image = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,1);
             memcpy(image->imageData,row[0],sizeof(char)*lengths[0]);
              image->ID =id;
              
              returnImage = image;

        }            
              
 
     }
     
     mysql_free_result(result);
      free(query);

     return returnImage;

}

/*string DBConnect::getSerializedSIFTFeatures(float* siftFeatures,int dimentionsLength){
    ostringstream os;
    int dataLength = sizeof(float) * dimentionsLength;
    os.write(reinterpret_cast<char *> (siftFeatures), dataLength);
    return os.str();
}*/

/*float* DBConnect::getDeSeraializedSIFTFeatures(const char* str, int dimentionsLength){
   
    int dataLength =  dimentionsLength; //sizeof(float) *
    int floatDataLength = dimentionsLength/sizeof(float);
    float* data = new float[floatDataLength];
    
    string* str2 = new string(str, dataLength);
    istringstream is(*str2);
    is.read(reinterpret_cast<char *> (data), dataLength);
    
    return data;
 }*/
/*bool DBConnect::storeSerializedSIFTFeatures(float* siftFeatures,int dimentionsLength){
   // conn->setAutoCommit(0);
  // try {
   

   
    
    string serializedString = getSerializedSIFTFeatures(siftFeatures,dimentionsLength);
    
   // std::string serializedString = "ab;c";
   
    int chunkSize = 2*serializedString.length()+1;
    char* chunk=(char*)malloc(sizeof(char)*chunkSize);    
    
    mysql_real_escape_string(conn, chunk, serializedString.c_str(), serializedString.length());

    char* stat = "INSERT INTO image (siftfeatures,timestamp) values('%s',now())";
    char* query=(char*)malloc(sizeof(char)*(strlen(stat)+chunkSize));
    int len = sprintf(query,stat, chunk);    
    
  
    mysql_real_query(conn, query, len);
    //mysql_close(conn);
    free(query);
    free(chunk);
    
    
    
    
  
  
    //mysql_query(conn,"INSERT INTO image (siftfeatures,timestamp) values('%s',now())");
    
   
  
    /*string querry  = "INSERT INTO image (siftfeatures,timestamp,no) values ('";//+serializedString+"',now())";
    querry +=serializedString;
    querry += "',now(),10)";*/
    //sql::SQLString* serializedStringSQL = new sql::SQLString(serializedString.c_str(),serializedString.length());
    /*sql::SQLString serializedStringSQL("ab;c");

    string querry  ="INSERT INTO image (siftfeatures,timestamp) values(?,now())";
   
    prep_stmt = conn->prepareStatement("INSERT INTO image (siftfeatures,timestamp) values(?,now())");
    */
    //istream *tmp_blob= new istringstream(serializedString,istringstream::binary);//, istringstream::in | istringstream::binary);

   //istream os = ;
   //stringstream tmp_blob(serializedString);
    //istream siftIstream(siftFeatures);
   /* int dataLength = sizeof(float) * dimentionsLength;
    os.write(reinterpret_cast<char *> (siftFeatures), dataLength);*/
    
   
    //Query query = conn->query();
   // prep_stmt = conn->prepareStatement("INSERT INTO image (siftfeatures,timestamp,no) values (?,now(),10)");
    // prep_stmt->setBlob(1,tmp_blob);
   // prep_stmt->setString(1,"abc");//*serializedStringSQL)
    //prep_stmt = conn->prepareStatement("INSERT INTO image (siftfeatures,timestamp,no) values ('"<<<<"',now(),10)");
  //  prep_stmt->setBlob(1,serializedString.);
   // prep_stmt->execute();
   // conn->commit();
/*} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line "<< __LINE__ << endl;
  cout << "# ERR Code: " << e.getErrorCode(); 
  cout << "# ERR: " << e.what(); 
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
  return false;
}* /
    return true;


}*/

/*
 float* DBConnect::retriveSerializedSIFTFeatures(int id){
 //http://lgallardo.com/en/2011/06/23/sentencias-preparadas-de-mysql-en-c-ejemplo-completo/
    // Bind variables
   // MYSQL_BIND param[1], result[1];

 
   unsigned long *lengths;

    //char* stat = "SELECT siftfeatures FROM image WHERE id=80";
    
    /* // Allocate statement handler
    stmt = mysql_stmt_init(conn);
    
    if (stmt == NULL) {
        print_error(conn, "Could not initialize statement handler");
        return;
    
    }
    
     // Prepare the statement
    if (mysql_stmt_prepare(stmt, sql, strlen(sql)) != 0) {
        print_stmt_error(stmt, "Could not prepare statement");
        return;
    }

     // Initialize the result column structures
    memset (param, 0, sizeof (param)); /* zero the structures * /
    memset (result, 0, sizeof (result)); /* zero the structures * /
    
     // Init param structure
 // Select
 param[0].buffer_type     = MYSQL_TYPE_INT24;
 param[0].buffer         = (void *) &id;
 param[0].is_unsigned    = 0;
 param[0].is_null         = 0;
 param[0].length         = 0;

 // Result
 result[0].buffer_type     = MYSQL_TYPE_LONG_BLOB;
 result[0].buffer         = (void *) &myNumAddresses;
 result[0].is_unsigned    = 0;
 result[0].is_null         = &is_null[0];
 result[0].length         = 0;

* /
    //int chunkSize = 2*serializedString.length()+1;
   // char* chunk=(char*)malloc(sizeof(char)*chunkSize);    
    
   // mysql_real_escape_string(conn, chunk, serializedString.c_str(), serializedString.length());
    //char* chunk = 
    char* sql = "SELECT siftfeatures FROM image WHERE id=%d";
    char* query=(char*)malloc(sizeof(char)*(strlen(sql)+sizeof(int)));
    int len = sprintf(query,sql, id);    
    
    mysql_query(conn, query);
    result = mysql_store_result(conn);
    row = mysql_fetch_row(result);
    lengths = mysql_fetch_lengths(result);

    float* deSerialFloat=0;
    if(row[0]!=NULL)
    {
        char* rowFromDB = (char*)malloc(sizeof(char)*lengths[0]);
        memcpy(rowFromDB,row[0],(sizeof(char)*lengths[0]));
       // sprintf(rowFromDB,"%s", row[0]);
        

        deSerialFloat=getDeSeraializedSIFTFeatures(rowFromDB,lengths[0]);
        //free(query);
        free(rowFromDB);
        
        
    //    free(query);
    }
    mysql_free_result(result);
    
    return deSerialFloat;
 }*/